package com.fg114.main.recorder;

import java.io.File;
import java.io.IOException;
import java.util.List;

import android.media.MediaRecorder;
import android.os.Environment;

import com.fg114.main.util.CheckUtil;
import com.rescueworkers.Settings;
import com.rescueworkers.Db.TaskDb;
import com.rescueworkers.dto.Task;
import com.rescueworkers.dto.UploadVoiceOrImageInfo;

public  class SoundMeter {
	static final private double EMA_FILTER = 0.6;

	private MediaRecorder mRecorder = null;
	private double mEMA = 0.0;
	public static String recordFilePath = android.os.Environment.getExternalStorageDirectory()+Settings.APP_PATH+Settings.RECORD_PATH;
	private String recordPath = "";
	private String fileName = "";

	public void start(String name) {
		if (!Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return;
		}
		this.fileName = name;
		if (mRecorder == null) {
			mRecorder = new MediaRecorder();
			mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			File recordFile = new File(recordFilePath);
			if(recordFile != null && !recordFile.exists()){
				try {
					recordFile.mkdir();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			recordPath = recordFilePath+"/"+name;
			mRecorder.setOutputFile(recordPath);
			try {
				mRecorder.prepare();
				mRecorder.start();
				
				mEMA = 0.0;
			} catch (IllegalStateException e) {
				System.out.print(e.getMessage());
			} catch (IOException e) {
				System.out.print(e.getMessage());
			}

		}
	}

	public void stop(Task task,List<UploadVoiceOrImageInfo> recordString,long recordStartTime) {
		if (mRecorder != null) {
			try {
				if(!CheckUtil.isEmpty(recordPath) && recordString != null){
					int recordTime  = (int)((System.currentTimeMillis() - recordStartTime)/1000);
					TaskDb.combineVoiceOrImageInfo(task, recordString, recordPath,fileName,1,recordTime);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			mRecorder.stop();
			mRecorder.release();
			mRecorder = null;
		}
	}

	public void pause() {
		if (mRecorder != null) {
			mRecorder.stop();
		}
	}

	public void start() {
		if (mRecorder != null) {
			mRecorder.start();
		}
	}

	public double getAmplitude() {
		if (mRecorder != null)
			return (mRecorder.getMaxAmplitude() / 2700.0);
		else
			return 0;

	}

	public double getAmplitudeEMA() {
		double amp = getAmplitude();
		mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
		return mEMA;
	}
}
